package com.sky.controller.client;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Blog;
import com.sky.domain.Tag;
import com.sky.domain.Type;
import com.sky.service.BlogService;
import com.sky.service.CommentService;
import com.sky.service.TagService;
import com.sky.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @GetMapping("/index")
    public String index(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                        Model model,@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){

        List<Type> typeList = typeService.getBlogType();
        List<Tag> tagList = tagService.getBlogTag();
        List<Blog> blogList = blogService.getAllRecommendBlog();
        PageHelper.startPage(pageNum,pageSize);
        List<Blog> allBlog = blogService.getAllBlog();
        PageInfo<Blog> pageInfo = new PageInfo<>(allBlog);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("types", typeList);
        model.addAttribute("tags", tagList);
        model.addAttribute("recommendBlogs", blogList);
        return "index";
    }

    @PostMapping("/search")
    public String search(String query,Model model,
                         @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        List<Blog> searchBlog = blogService.getSearchBlog(query);
        PageHelper.startPage(pageNum,5);
        PageInfo<Blog> pageInfo = new PageInfo<>(searchBlog);
        model.addAttribute("pageInfo",pageInfo);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blogDetail(@PathVariable("id") Long id,Model model){
        Blog blog = blogService.getBlogById(id);
        model.addAttribute("blog",blog);
        return "blog";
    }

}
